<template>
  <el-dialog title="推流" :visible.sync="liveVisible" width="50%">
    <div>
      <div>
        <button @click="startRecording">开始录制并推流</button>
        <!-- 这里可以放置需要录制的页面内容 -->
        <div id="content-to-record">
          <!-- 比如一些文本、图片等构成的页面展示内容 -->
          <h1>示例页面内容</h1>
          <img src="https://cdn.mlhk.com/mledu/2023/6/29/4733/PCM_1688007033403.7922.jpg" alt="示例图片" />
        </div>
      </div>
      <!-- <h1>屏幕共享与截图示例</h1>
      <button @click="startScreenShare">开始屏幕共享</button>
      <button @click="stopScreenShare" :disabled="!isSharing">停止屏幕共享</button>
      <button @click="captureScreenshot" :disabled="!isSharing">截图</button>
      <video ref="screenVideo" autoplay playsinline style="width: 100%; height: auto; border: 1px solid #ddd;"></video>
      <div v-if="screenshot">
        <h2>截图结果：</h2>
        <img :src="screenshot" alt="截图" style="max-width: 100%; border: 1px solid #ddd;" />
      </div>
      <div style="margin: 10px 0;">
        <el-input placeholder="请输入webRtc推流地址" v-model="liveParam.obsServer" disabled></el-input>
      </div>
      <div id="id_local_video" style="width: 500px;max-height:450px;border: 2px solid red;background: blue;">
        <div style="height: 200px;"><h1>这是测试画面比分栏</h1></div>
      </div>
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="beginPush" v-if="!isPlay">开始推流</el-button>
        <el-button type="primary" @click="stopPush" v-else>停止推流</el-button>
      </div> -->
    </div>
  </el-dialog>
</template>

<script>
import { getLive } from '../../api/table.js'
import html2canvas from 'html2canvas'
import RecordRTC from 'recordrtc'
export default {
  data() {
    return {
      isSharing: false, // 是否正在共享屏幕
      mediaStream: null, // 媒体流对象
      screenshot: null, // 截图的 base64 数据
      liveVisible: false,
      liveParam: {},
      livePusher: null,
      isPlay: false,
      //
      stream: null,
      recorder: null,
      pusher: null // 新增用于存放TXLivePusher实例
    }
  },
  created() {
    this.readyPusher()
  },
  mounted() {},
  methods: {
    async startRecording() {
      const canvas = await html2canvas(document.getElementById('content-to-record'))
      const stream = canvas.captureStream()
      this.stream = stream
      this.recorder = new RecordRTC(stream, {
        type: 'video'
      })
      this.recorder.startRecording()
      setTimeout(() => {
        this.stopRecordingAndPushToTencentCloud()
      }, 10000)
    },
    stopRecordingAndPushToTencentCloud() {
      this.recorder.stopRecording(async () => {
        const blob = this.recorder.getBlob()
        const videoUrl = URL.createObjectURL(blob)

        let that = this
        // 创建腾讯云推流实例（这里假设你已经按照要求正确引入了相关SDK等）
        // eslint-disable-next-line no-undef
        this.livePusher = new TXLivePusher({
          // 填入真实的推流域名和流名称，按腾讯云要求配置
          pushUrl: that.liveParam.obsServer,
          video: {
            width: 640,
            height: 480,
            frameRate: 25,
            bitrate: 800
          },
          audio: {
            sampleRate: 44100,
            channels: 1
          }
        })

        // 配置推流相关参数，这里示例设置了一些基本的参数，可按需调整
        const pushConfig = {
          videoFps: 25, // 视频帧率
          videoBitrate: 800, // 视频码率（单位kbps）
          audioSampleRate: 44100, // 音频采样率
          audioChannels: 1 // 声道数
          // 其他可能的参数可以根据腾讯云文档继续添加
        }

        // 监听推流状态相关事件，方便处理各种情况
        // this.livePusher.on(TXLivePusher.EVENT_PUSH_BEGIN, (event) => {
        //   console.log('推流开始');
        // });
        // this.livePusher.on(TXLivePusher.EVENT_PUSH_ERR, (event) => {
        //   console.error('推流出错:', event.detail.errCode, event.detail.errMsg);
        // });
        // this.livePusher.on(TXLivePusher.EVENT_PUSH_END, (event) => {
        //   console.log('推流结束');
        //   // 推流结束后释放资源等操作
        //   this.livePusher.destroy();
        // });

        // 创建video元素用于播放视频流，绑定视频流源
        const videoElement = document.createElement('video')
        videoElement.src = videoUrl
        videoElement.muted = true // 通常静音处理
        videoElement.addEventListener('loadedmetadata', () => {
          videoElement.play()
          // 使用startPush方法进行推流，传入video元素和配置参数
          that.livePusher.startPush(videoElement, pushConfig)
        })
      })
    },
    // async startRecording() {
    //   // 获取屏幕内容作为视频流
    //   const displayMediaStream = await navigator.mediaDevices.getDisplayMedia({
    //     video: true,
    //     audio: true
    //   })

    //   // 创建一个Canvas元素用于绘制屏幕内容
    //   const canvas = document.createElement('canvas')
    //   const ctx = canvas.getContext('2d')

    //   // 设置Canvas尺寸
    //   canvas.width = 1280
    //   canvas.height = 720

    //   // 将视频流的第一帧渲染到Canvas上
    //   const video = document.createElement('video')
    //   video.srcObject = displayMediaStream
    //   video.play()

    //   function render() {
    //     if (video.readyState === video.HAVE_ENOUGH_DATA) {
    //       ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
    //       setTimeout(render, 30) // 每秒30帧
    //     }
    //   }
    //   render()

    //   // 创建MediaStream Recorder
    //   const recorder = new MediaRecorder(displayMediaStream, {
    //     mimeType: 'video/webm'
    //   })

    //   // 处理录制的数据
    //   let chunks = []
    //   recorder.ondataavailable = event => {
    //     if (event.data && event.data.size > 0) {
    //       chunks.push(event.data)
    //     }
    //   }

    //   recorder.onstop = () => {
    //     const blob = new Blob(chunks, { type: 'video/webm' })
    //     chunks = []
    //     const url = URL.createObjectURL(blob)
    //     // 创建一个视频元素来播放录制的内容
    //     const videoElement = document.createElement('video')
    //     videoElement.src = url
    //     videoElement.controls = true
    //     document.body.appendChild(videoElement)
    //   }

    //   // 开始录制，点击按钮停止
    //   recorder.start()
    //   // 停止录制
    //   // recorder.stop();
    // },
    //初始化腾讯推流组件
    // readyPusher() {
    //   // eslint-disable-next-line no-undef
    //   this.livePusher = new TXLivePusher()
    // },
    openDialog(row) {
      getLive({
        tournamentId: row.id,
        endTime: this.getFormattedDatePlusOneDay(),
        type: 2
      }).then(res => {
        console.log('res', res)
        if (res.code == 200) {
          this.liveParam = res.data
          this.liveVisible = true
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 当前时间加1天
    getFormattedDatePlusOneDay() {
      const now = new Date()
      now.setDate(now.getDate() + 1) // 增加1天
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要+1
      const date = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
    },
    beginPush() {
      //  'webrtc://pushlive.yundongshugenlive.cn/live/185qVSD8p?txSecret=c845b2962df69caa1fdabcc4759a4b80&txTime=677BC619'
      // eslint-disable-next-line no-undef
      // var livePusher = new TXLivePusher()
      let that = this
      let livePusher = this.livePusher
      console.log(livePusher)
      livePusher.setRenderView('id_local_video')
      // 设置视频质量
      livePusher.setVideoQuality('720p')
      // 设置音频质量
      livePusher.setAudioQuality('standard')
      // 自定义设置帧率
      livePusher.setProperty('setVideoFPS', 25)

      // 采集完摄像头和麦克风之后自动推流  livePusher.startCamera(),
      Promise.all([livePusher.startMicrophone()]).then(function() {
        livePusher.startPush(that.liveParam.obsServer)
      })

      // 采集完摄像头和麦克风之后自动推流  , livePusher.startMicrophone()
      // Promise.all([livePusher.startScreenCapture()])
      //   .then(function() {
      //     //传入的是一个推流地址，后端返回的 webrtc推流链接地址
      //     livePusher
      //       .startPush(that.liveParam.obsServer)
      //       .then(() => {
      //         that.isPlay = true
      //         console.log('pushing')
      //         if (livePusher.isPushing()) {
      //           console.log('pushing')
      //         }
      //       })
      //       .catch(err => {
      //         console.log(err)
      //       })
      //   })
      //   .catch(err => {
      //     console.log(err)
      //     // if (err == 'Error: video track is existed') {
      //     //   that.$message.warning('请先手动停止上方的停止共享按钮 再重新推流')
      //     // }
      //   })
    },
    async stopPush() {
      this.isPlay = false
      // 停止推流
      this.livePusher.stopPush()
      setTimeout(() => {
        location.reload()
      }, 1000)
      // // 关闭摄像头
      // this.livePusher.stopCamera()
      // // 关闭麦克风
      // this.livePusher.stopMicrophone()
      // 创建RTCPeerConnection对象
      // this.peerConnection = new RTCPeerConnection();
      // // 将屏幕流的轨道添加到RTCPeerConnection中
      // this.screenStream.getTracks().forEach(track => {
      //   this.peerConnection.addTrack(track, this.screenStream);
      // });
      // let peerConnection = new RTCPeerConnection()
      // console.log('peerConnection', peerConnection)
      // let videoEffectManager = this.livePusher.getVideoEffectManager()
      // console.log('videoEffectManager', videoEffectManager)
    },
    //
    async startScreenShare() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
        alert('当前浏览器不支持屏幕共享功能。请使用最新版本的谷歌浏览器。')
        return
      }

      try {
        // 调用 getDisplayMedia 获取屏幕媒体流
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            cursor: 'always' // 是否显示鼠标指针
          },
          audio: false // 是否捕获音频
        })

        this.mediaStream = stream
        this.isSharing = true

        // 将媒体流绑定到 <video> 元素
        const videoElement = this.$refs.screenVideo
        if (videoElement) {
          videoElement.srcObject = stream
        }

        // 监听屏幕共享停止事件
        stream.getVideoTracks()[0].addEventListener('ended', () => {
          this.stopScreenShare()
        })
      } catch (error) {
        console.error('屏幕共享失败:', error)
        alert('屏幕共享失败，请检查权限设置。')
      }
    },
    stopScreenShare() {
      if (this.mediaStream) {
        // 停止所有媒体流轨道
        this.mediaStream.getTracks().forEach(track => track.stop())
        this.mediaStream = null
      }
      this.isSharing = false

      // 停止视频播放
      const videoElement = this.$refs.screenVideo
      if (videoElement) {
        videoElement.srcObject = null
      }
    },
    captureScreenshot() {
      if (!this.isSharing) {
        alert('请先开始屏幕共享！')
        return
      }

      const videoElement = this.$refs.screenVideo
      if (!videoElement) {
        alert('视频元素未找到！')
        return
      }

      // 创建一个 canvas，用于绘制视频帧
      const canvas = document.createElement('canvas')
      canvas.width = videoElement.videoWidth
      canvas.height = videoElement.videoHeight

      const context = canvas.getContext('2d')
      context.drawImage(videoElement, 0, 0, canvas.width, canvas.height)

      // 生成 base64 图片数据
      this.screenshot = canvas.toDataURL('image/png')

      // 可选：下载截图
      this.downloadImage(this.screenshot, 'screenshot.png')
    },
    downloadImage(dataUrl, fileName) {
      const link = document.createElement('a')
      link.href = dataUrl
      link.download = fileName
      link.click()
    }
  }
}
</script>

<style>
button {
  margin: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>
